package controller

import (
	"strings"

	"github.com/gogf/gf/v2/net/ghttp"

	"goldtree/internal/service"
	"goldtree/utility/response"
)

// UserController 用户控制器
type UserController struct{}

var UserCtrl = UserController{}

// Register 用户注册
func (c *UserController) Register(r *ghttp.Request) {
	var req *service.RegisterReq
	if err := r.Parse(&req); err != nil {
		response.ErrorExit(r, "参数解析失败: "+err.Error())
		return
	}

	user, err := service.User.Register(r.Context(), req)
	if err != nil {
		response.ErrorExit(r, err.Error())
		return
	}

	response.SuccessExit(r, user)
}

// Login 用户登录
func (c *UserController) Login(r *ghttp.Request) {
	var req *service.LoginReq
	if err := r.Parse(&req); err != nil {
		response.ErrorExit(r, "参数解析失败: "+err.Error())
		return
	}

	result, err := service.User.Login(r.Context(), req)
	if err != nil {
		response.ErrorExit(r, err.Error())
		return
	}

	response.SuccessExit(r, result)
}

// RefreshToken 刷新访问令牌
func (c *UserController) RefreshToken(r *ghttp.Request) {
	var req *service.RefreshTokenReq
	if err := r.Parse(&req); err != nil {
		response.ErrorExit(r, "参数解析失败: "+err.Error())
		return
	}

	result, err := service.User.RefreshToken(r.Context(), req)
	if err != nil {
		response.ErrorExit(r, err.Error())
		return
	}

	response.SuccessExit(r, result)
}

// Logout 用户登出
func (c *UserController) Logout(r *ghttp.Request) {
	// 从请求头获取令牌
	token := c.getTokenFromRequest(r)
	if token == "" {
		response.ErrorExit(r, "未提供访问令牌")
		return
	}

	err := service.User.Logout(r.Context(), token)
	if err != nil {
		response.ErrorExit(r, err.Error())
		return
	}

	response.SuccessExit(r, "登出成功")
}

// GetProfile 获取个人信息
func (c *UserController) GetProfile(r *ghttp.Request) {
	// 从上下文获取用户ID（由认证中间件设置）
	userId := c.getUserIdFromContext(r)
	if userId == 0 {
		response.ErrorExit(r, "未找到用户信息")
		return
	}

	user, err := service.User.GetProfile(r.Context(), userId)
	if err != nil {
		response.ErrorExit(r, err.Error())
		return
	}

	response.SuccessExit(r, user)
}

// UpdateProfile 更新个人信息
func (c *UserController) UpdateProfile(r *ghttp.Request) {
	// 从上下文获取用户ID
	userId := c.getUserIdFromContext(r)
	if userId == 0 {
		response.ErrorExit(r, "未找到用户信息")
		return
	}

	var req *service.UpdateProfileReq
	if err := r.Parse(&req); err != nil {
		response.ErrorExit(r, "参数解析失败: "+err.Error())
		return
	}

	user, err := service.User.UpdateProfile(r.Context(), userId, req)
	if err != nil {
		response.ErrorExit(r, err.Error())
		return
	}

	response.SuccessExit(r, user)
}

// ChangePassword 修改密码
func (c *UserController) ChangePassword(r *ghttp.Request) {
	// 从上下文获取用户ID
	userId := c.getUserIdFromContext(r)
	if userId == 0 {
		response.ErrorExit(r, "未找到用户信息")
		return
	}

	var req *service.ChangePasswordReq
	if err := r.Parse(&req); err != nil {
		response.ErrorExit(r, "参数解析失败: "+err.Error())
		return
	}

	err := service.User.ChangePassword(r.Context(), userId, req)
	if err != nil {
		response.ErrorExit(r, err.Error())
		return
	}

	response.SuccessExit(r, "密码修改成功")
}

// ValidateToken 验证令牌（用于前端检查登录状态）
func (c *UserController) ValidateToken(r *ghttp.Request) {
	// 从请求头获取令牌
	token := c.getTokenFromRequest(r)
	if token == "" {
		response.ErrorExit(r, "未提供访问令牌")
		return
	}

	user, err := service.User.ValidateToken(r.Context(), token)
	if err != nil {
		response.ErrorExit(r, err.Error())
		return
	}

	response.SuccessExit(r, user)
}

// GetUserInfo 获取用户信息（通过令牌）
func (c *UserController) GetUserInfo(r *ghttp.Request) {
	// 从上下文获取用户信息（由认证中间件设置）
	user := c.getUserFromContext(r)
	if user == nil {
		response.ErrorExit(r, "未找到用户信息")
		return
	}

	response.SuccessExit(r, user)
}

// getTokenFromRequest 从请求头获取令牌
func (c *UserController) getTokenFromRequest(r *ghttp.Request) string {
	// 从Authorization头获取
	authHeader := r.Header.Get("Authorization")
	if authHeader != "" {
		// Bearer Token格式: Bearer <token>
		parts := strings.SplitN(authHeader, " ", 2)
		if len(parts) == 2 && strings.ToLower(parts[0]) == "bearer" {
			return parts[1]
		}
	}
	
	// 从X-Token头获取
	token := r.Header.Get("X-Token")
	if token != "" {
		return token
	}
	
	// 从查询参数获取
	token = r.Get("token").String()
	if token != "" {
		return token
	}
	
	return ""
}

// getUserIdFromContext 从上下文获取用户ID
func (c *UserController) getUserIdFromContext(r *ghttp.Request) int {
	userId := r.GetCtxVar("user_id")
	if userId != nil {
		if id, ok := userId.Val().(int); ok {
			return id
		}
	}
	return 0
}

// getUserFromContext 从上下文获取用户信息
func (c *UserController) getUserFromContext(r *ghttp.Request) interface{} {
	user := r.GetCtxVar("user")
	if user != nil {
		return user.Val()
	}
	return nil
}